//
//  CommonModule.m
//  baseapp
//
//  Created by CaigaoXiao on 17/3/22.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "CommonModule.h"
#import "SharedItem.h"
#import <React/UIView+React.h>
//#import "AppDelegate.h"
#import "WXApi.h"
//#import "AppDelegate.h"
//#import "Constant.h"
#import <CommonCrypto/CommonDigest.h>
#import "ATAppUpdater/ATAppUpdater.h"

#define INVOKE_FAILED (@"WeChat API invoke returns false.")



@implementation CommonModule

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE();


RCT_EXPORT_METHOD(share:(NSDictionary *) map resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    // var obj = new Object();
    // obj.cmd = "1";  // 固定参数
    // obj.prefix = "wxfx9gt_"; //前缀
    // obj.desc = "分享的文字";
    // obj.imgs =
    //     [
    //         'http://cdn.img.ecduo.cn/ecduo/Uploads/Picture/2016-09/57e3c7cd2ece3.jpg',
    //         "http://cdn.img.ecduo.cn/ecduo/Uploads/Picture/2016-09/57e3c7cd2ece3.jpg"
    //     ];
  @try {
    RCTLogInfo(@"==share===map %@", map);
    if([[map objectForKey:@"cmd"] isEqualToString:@"1"]){
      
        NSArray * arr=[map objectForKey:@"imgs"];
        NSMutableArray *array = [[NSMutableArray alloc]init];
        for(int i=0;i<arr.count;i++){
          NSString *URL = arr[i];
          [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
          NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:URL]];
          UIImage *imagerang = [UIImage imageWithData:data];
          NSString *path_sandox = NSHomeDirectory();
          NSString *imagePath = [path_sandox stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@%d.jpg",[map objectForKey:@"prefix"],i]];
          [UIImagePNGRepresentation(imagerang) writeToFile:imagePath atomically:YES];
          NSURL *shareobj = [NSURL fileURLWithPath:imagePath];
          /** 这里做个解释 imagerang : UIimage 对象 shareobj:NSURL 对象 这个方法的实际作用就是 在调起微信的分享的时候 传递给他 UIimage对象,在分享的时候 实际传递的是 NSURL对象 达到我们分享九宫格的目的 */
           RCTLogInfo(@"==share===shareobj %@,%d", shareobj,i);
          SharedItem *item = [[SharedItem alloc] initWithData:imagerang andFile:shareobj];
          [array addObject:item];
         // RCTLogInfo(@"==share===array %@", array);
          if(i==8) break;
        }
        UIActivityViewController *activityViewController =[[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil];
        //尽量不显示其他分享的选项内容
        activityViewController.excludedActivityTypes = @[ UIActivityTypePostToFacebook,UIActivityTypePostToTwitter, UIActivityTypePostToWeibo, UIActivityTypeMessage,UIActivityTypeMail,UIActivityTypePrint,UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll,UIActivityTypeAddToReadingList,UIActivityTypePostToFlickr,UIActivityTypePostToVimeo,UIActivityTypePostToTencentWeibo,UIActivityTypeAirDrop,UIActivityTypeOpenInIBooks];

       // RCTLogInfo(@"==share===222 %@", @"");
        if (activityViewController) {
         // RCTLogInfo(@"==share==activityViewController=222 %@", @"");
          UIViewController *rootController = UIApplication.sharedApplication.delegate.window.rootViewController;
          dispatch_async(dispatch_get_main_queue(), ^{
              [rootController presentViewController:activityViewController animated:YES completion:nil];
          });
        }
    }
    resolve(@"0000");
  } @catch (NSException *exception) {
    reject(@"0001",@"error",[NSError errorWithDomain:@"error" code:0001 userInfo:nil]);
  }
  
}


RCT_EXPORT_METHOD(getHttpCacheSize:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
  NSURLCache *httpCache = [NSURLCache sharedURLCache];
  resolve(@([httpCache currentDiskUsage]));
}
RCT_EXPORT_METHOD(onToUpdateApp:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){
  [[ATAppUpdater sharedUpdater] showUpdateWithConfirmation];////app更新
   resolve(@"0000");
}

RCT_EXPORT_METHOD(clearCache:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
  NSURLCache *httpCache = [NSURLCache sharedURLCache];
  [httpCache removeAllCachedResponses];
  resolve(@"0000");
}


RCT_EXPORT_METHOD(getImageCacheSize:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
  resolve(@"0");
}

RCT_EXPORT_METHOD(clearImageCache:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
{
  resolve(@"0000");
}

RCT_EXPORT_METHOD(wxpay:(NSDictionary *) map resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
  NSString *type=[map objectForKey:@"type"];
  int num = [type intValue];
   RCTLogInfo(@"==wxpay==args== %@", map);
  PayReq *payReq   = [[PayReq alloc] init];
  if(1==num){
    //payReq.openID = [map objectForKey:@"appid"];
    payReq.partnerId = [map objectForKey:@"partnerid"];
    payReq.prepayId  = [map objectForKey:@"prepayid"];
    payReq.package   = [map objectForKey:@"package"];
    payReq.nonceStr  = [map objectForKey:@"noncestr"];
    NSString * stamp = [map objectForKey:@"timestamp"];
    //NSTimeInterval interval=[[NSDate date] timeIntervalSince1970]*1000;
    payReq.timeStamp = stamp.intValue;
    //RCTLogInfo(@"==wxpay==timeStamp:%d",payReq.timeStamp);
    NSString *str = [[NSString alloc] initWithString:
                     [NSString stringWithFormat:@"appid=%@&noncestr=%@&package=%@&partnerid=%@&prepayid=%@&timestamp=%d&key=%@",
                      [map objectForKey:@"appid"], payReq.nonceStr,payReq.package,payReq.partnerId,payReq.prepayId,payReq.timeStamp,[map objectForKey:@"wxkey"]]];
    RCTLogInfo(@"==wxpay==md5-str:%@",str);
    NSString *sign=[[self md5:str] uppercaseString];
    RCTLogInfo(@"==wxpay==sign:%@",sign);
    payReq.sign = sign;
  }else{
    payReq.partnerId=[map objectForKey:@"partnerid"];
    payReq.prepayId=[map objectForKey:@"prepayid"];
    payReq.package=[map objectForKey:@"package"];
    payReq.nonceStr=[map objectForKey:@"noncestr"];
    NSString * stamp = [map objectForKey:@"timestamp"];
    payReq.timeStamp=stamp.intValue;
    payReq.sign=[map objectForKey:@"sign"];
   
  }
  
  void ( ^ completion )( BOOL );
    completion = ^( BOOL success )
    {
      if(success){
        resolve(@"0000");
      }else{
         reject(@"0001",@"error",[NSError errorWithDomain:@"error" code:0001 userInfo:nil]);
      }
        return;
    };
//    [WXApi sendReq:payReq completion:completion];
  
  
  //发送请求到微信，等待微信返回onResp  //升级之后不能用的问题
  //  if([WXApi sendReq:payReq]){
  //    resolve(@"0000");
  //  }else{
  //    reject(@"0001",@"error",[NSError errorWithDomain:@"error" code:0001 userInfo:nil]);
  //  }
  
}

- (NSString *) md5:(NSString *) input {
  const char *cStr = [input UTF8String];
  unsigned char digest[CC_MD5_DIGEST_LENGTH];
  CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call
  NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    [output appendFormat:@"%02x", digest[i]];
  
  return output;
}


@end


